package com.technology.education.base

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.*
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.setPadding
import androidx.core.widget.doAfterTextChanged
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.angcyo.dsladapter.*
import com.technology.education.R
import com.technology.education.dslitem.AppStatusItem
import com.technology.education.ext.*
import com.technology.education.widget.CommonButton
import com.technology.education.widget.MyRecylcerView
import me.hgj.jetpackmvvm.base.fragment.BaseVmFragment
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.util.dp2px

/**
 *@author:create by BZY
 *Date: 2020/5/29 17
 */
abstract class BaseRecyclerTopBarFragment<VM : BaseViewModel> :
    BaseVmFragment<VM>() {


    /**提供悬停功能*/
    var hoverItemDecoration = HoverItemDecoration()

    /**提供基本的分割线功能*/
    var baseDslItemDecoration = DslItemDecoration()

    lateinit var recycler: MyRecylcerView
    var myAdapter: DslAdapter = DslAdapter().apply {
        dslAdapterStatusItem = AppStatusItem()
    }

    override fun layoutId(): Int = R.layout.fragment_recyclerview_toobar
    override fun initView(savedInstanceState: Bundle?) {
        initSwipe()
        initVertical()
        initRefresh()
        initViews()
        view?.findViewById<Toolbar>(R.id.toolbar)?.apply {
            setNavigationOnClickListener {
                onBack()
            }
        }
        initLoadMore()
    }

    fun setToolBarRight(res:Int,click: () -> Unit){
        requireView().findViewById<Toolbar>(R.id.toolbar)?.apply {
            setHasOptionsMenu(true)
            inflateMenu(res)
            setOnMenuItemClickListener {
                click.invoke()
                false
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
    }

    fun initSearch(hintS: String? = "") {
        view?.findViewById<View>(R.id.line)?.visibility = View.VISIBLE
        var searchView = EditText(context)
        searchView.apply {
            background = getResId(R.drawable.circle_gray_bg_50)
            textSize = 16f
            hint = hintS
            isFocusable = true
            isFocusableInTouchMode = true
            setTextColor(getColor(R.color.text_h))
            setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher_foreground, 0, 0, 0)
            setPadding(30, 0, 20, 0)
            compoundDrawablePadding = 20
            doAfterTextChanged {
                onAfterTextChanged(it)
            }
            isSingleLine = true
            imeOptions = EditorInfo.IME_ACTION_SEARCH
            setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(
                    v: TextView?,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        search()
                        closeInput()
                        return true
                    }
                    return false
                }

            })
        }

        view?.findViewById<LinearLayout>(R.id.ll_top)?.addView(searchView)
        searchView.postDelayed({
            showInput(searchView)
        }, 300)

    }

    fun setBottomButton(content: String, click: () -> Unit) {
        bottomContent().apply {
            removeAllViews()
            setPadding(12 * dpi)
            addView(CommonButton(requireContext()).apply {
                text = content
                textSize=16f
                setOnClickListener {
                    click.invoke()
                }
            }, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(45)))
        }
    }

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    fun showInput(et: EditText) {
        et.requestFocus()
        val imm =
            requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm!!.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT)
    }

    /**
     * 软键盘搜索监听
     */
    open fun search() {

    }

    /**
     * 监听搜索输入时间
     */
    open fun onAfterTextChanged(it: Editable?) {

    }

    fun setTitle(title: String) {
        view?.findViewById<TextView>(R.id.tv_title)?.text = title
    }

    fun noToolbarBack() {
        view?.findViewById<Toolbar>(R.id.toolbar)?.navigationIcon = null
    }

    @SuppressLint("RestrictedApi")
    fun setTitle(title: String, right: String) {
        view?.findViewById<TextView>(R.id.tv_title)?.text = title
    }

    fun bottomContent(): LinearLayout {
        return requireView().findViewById(R.id.ll_content)
    }

    fun onRightClick() {

    }

    /**
     * 返回上页
     */
    open fun onBack() {
        closeInput()
        findNavController().navigateUp()
    }

    /**
     * 初始化刷新swipe控件，默认关闭刷新功能
     */
    private fun initSwipe() {
        view?.findViewById<SwipeRefreshLayout>(R.id.base_refresh_layout)?.apply {
            isEnabled = false
            setProgressViewOffset(true, 0, 50)
        }
    }


    /**
     * 初始化为垂直列表
     */
    private fun initVertical() {
        view?.findViewById<MyRecylcerView>(R.id.rv_list)?.apply {
            recycler = this
            addItemDecoration(baseDslItemDecoration)
            hoverItemDecoration.attachToRecyclerView(this)
            setHasFixedSize(true)
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = myAdapter
        }
    }

    fun initGrid(count: Int) {
        recycler.layoutManager = gridLayout(requireContext(), myAdapter, count)
    }

    fun initLoadMore() {
        myAdapter.dslLoadMoreItem.onLoadMore = {
            loadMore()
        }

    }

    override fun showLoading(message: String) {
        showLoadingExt(message = message)
    }

    /**
     * 启动重载数据功能
     */
    fun initRefresh() {
        myAdapter.dslAdapterStatusItem.onRefresh = {
            refreshData()
        }
    }

    /**
     * 开启下拉刷新
     */
    fun enableSwipe() {
        view?.findViewById<SwipeRefreshLayout>(R.id.base_refresh_layout)?.apply {
            isEnabled = true
            setOnRefreshListener {
                refreshData()
            }
        }
    }

    override fun dismissLoading() {
        loadFinish()
        dismissLoadingExt()
    }

    fun loading() {
        myAdapter.render {
            updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_LOADING)
        }
    }

    fun loadFinish() {
        refreshDone()
        myAdapter.setAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_NONE)
    }

    fun loadEmpty() {
        refreshDone()
        myAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_EMPTY)
    }

    fun loadError() {
        refreshDone()
        myAdapter.updateAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_ERROR)
    }

    fun hasMore(more: Boolean) {
        myAdapter.setLoadMoreEnable(more)
    }

    fun hasMore(total: Int) {
        myAdapter.setLoadMoreEnable(total > mViewModel.pageIndex * mViewModel.pageSize)
    }

    fun showToast(content: String) {
        toast(content)
    }

    fun refreshDone() {
        view?.findViewById<SwipeRefreshLayout>(R.id.base_refresh_layout)?.isRefreshing = false
    }

    /**
     * 关闭软键盘
     */
    open fun closeInput() {
        val inputMethodManager =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputMethodManager != null && requireActivity().currentFocus != null) {
            inputMethodManager.hideSoftInputFromWindow(
                requireActivity().currentFocus
                !!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    abstract fun initViews()
    abstract override fun lazyLoadData()
    fun loadMore() {
        mViewModel.loadMore()
    }

    open fun refreshData() {
        mViewModel.refresh()
    }

    abstract override fun createObserver()

    open fun renderAdapter(renders: DslAdapter.() -> Unit) {
        myAdapter.render {
            renders()
        }
    }
}